package console

import (
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"iot/plat/device"
	"iot/plat/protocol"
	"net/http"
)

// StartServer 启动HTTP服务器
func StartConsole() error {
	ip := viper.GetString("console.ip")
	port := viper.GetString("console.port")
	r := gin.Default()
	err := r.SetTrustedProxies(nil)
	if err != nil {
		return err
	}

	// 添加设备组相关路由
	deviceGroup := r.Group("/device")
	{
		deviceGroup.POST("/start/:protocol_index", DeviceStart)
		deviceGroup.GET("/show/:device_name", DeviceShow)
		deviceGroup.GET("/argshow/:arg/:rt", ArgShow)
		deviceGroup.GET("/groupshow/:group/:rt", GroupShow)
	}

	go func() {
		if err := r.Run(ip + ":" + port); err != nil {
		}
	}()
	return nil
}

func DeviceStart(c *gin.Context) {
	// 使用匿名结构体解析请求JSON
	ProtocolIndex := c.Param("protocol_index")
	if ProtocolIndex == "" {
		c.String(http.StatusBadRequest, "ProtocolIndex is empty!")
	}
	if err := protocol.GetChannelMgr().Start(ProtocolIndex); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status": "Device started",
	})
}

func DeviceShow(c *gin.Context) {
	deviceName := c.Param("device_name")
	if deviceName == "" {
		c.String(http.StatusBadRequest, "device_name is empty!")
		return
	}

	if device.GetDeviceMgr().Device(deviceName) == nil {
		c.String(http.StatusNotFound, "device not found!")
		return
	}

	c.JSON(http.StatusOK, gin.H{"msg": device.GetDeviceMgr().Device(deviceName).Show()})
}

func GroupShow(c *gin.Context) {
	groupIdx := c.Param("group")
	rt := c.Param("rt")
	if groupIdx == "" {
		c.String(http.StatusBadRequest, "group is empty!")
		return
	}

	var isRt bool
	if rt == "true" {
		isRt = true
	}

	dev := device.GetDeviceMgr().DeviceByGroupIndex(groupIdx)
	if dev == nil {
		c.String(http.StatusNotFound, "device not found!")
		return
	}

	c.JSON(http.StatusOK, gin.H{"msg": dev.ShowGroup(groupIdx, isRt)})
}

func ArgShow(c *gin.Context) {
	argIdx := c.Param("arg")
	rt := c.Param("rt")
	if argIdx == "" {
		c.String(http.StatusBadRequest, "arg is empty!")
		return
	}

	var isRt bool
	if rt == "true" {
		isRt = true
	}

	dev := device.GetDeviceMgr().DeviceByArgIndex(argIdx)
	if dev == nil {
		c.String(http.StatusNotFound, "device not found!")
		return
	}

	arg := dev.Argument(argIdx)
	if arg == nil {
		c.String(http.StatusNotFound, "arg not found!")
		return
	}

	c.JSON(http.StatusOK, gin.H{"msg": arg.Show(isRt)})
}
